﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.SessionState;
using RN.ERP.Web.ModelService;
using Fly.Common.Linq;
using Newtonsoft.Json;
using System.Configuration;

namespace RN.ERP.Web.Handlers
{
    /// <summary>
    /// UserInfoHandler 的摘要说明
    /// </summary>
    public class UserInfoHandler : IHttpHandler, IRequiresSessionState
    {
        private HttpContext _context;
        private SessionUserInfo currentUser;

        public void ProcessRequest(HttpContext context)
        {
            _context = context;
            currentUser = (SessionUserInfo)context.Session[SessionConstant.SESSION_USERINFO];
            MethodRoute();
        }

        /// <summary>
        /// Method路由
        /// </summary>
        private void MethodRoute()
        {
            string action = _context.Request.Params["action"].Trim().ToLower();
            switch (action)
            {
                case "changepwd":
                    ChangePwd(); 
                    break;
                case "resetorginazationcode":
                    ResetOrginazationCode(); 
                    break;
                case "getuserinfo":
                    GetUserInfo(); 
                    break;
                case "getorgdata":
                    GetOrgData();
                    break;
               
                default: break;
            }
        }
        
        /// <summary>
        /// 获取用户基本信息
        /// </summary>
        private void GetUserInfo()
        {
            string UserName = currentUser.UserName;
            string Name = currentUser.Name;
            string UserType = string.Empty;
            string Tel = "";
            string Email = "";
            string RoleType = currentUser.RoleType.ToLower();

            if (RoleType == "user")
            {
                UserType = UtilitiesTool.CorpTypeDic[currentUser.RoleId.ToString()];
                EnterpriseService.EnterpriseServiceClient esc = new EnterpriseService.EnterpriseServiceClient();
                IList<QueryCompanyInfoCondition> condition = new List<QueryCompanyInfoCondition> 
                {
                    new QueryCompanyInfoCondition
                    {
                        CorpUserGuid = new ParameterValue<Guid>
                        {
                            O = OptEnum.Equal, V = new Guid(currentUser.CorpUserGuid)
                        }
                    }
                };
                string corpStr = esc.GetCompanyInfo(JsonConvert.SerializeObject(condition), currentUser.AreaCode);
                Tb_Corp_CompanyInfo corp = JsonConvert.DeserializeObject<Tb_Corp_CompanyInfo>(corpStr);
                Email = corp.Email;
            }
            var rst = new { UserName = UserName, Name = Name, UserType = UserType, Tel = Tel, Mail = Email, RoleType = RoleType };
            Print(JsonConvert.SerializeObject(rst));
        }

        /// <summary>
        /// 修改密码
        /// </summary>
        private void ChangePwd()
        {
            string userGuid = currentUser.CorpUserGuid;
            string areaCode = currentUser.AreaCode;
            string newPwd = _context.Request.Params["newPwd"];

            using (BasicService.BasicServiceClient client = new BasicService.BasicServiceClient())
            {
                bool rst = client.ResetPassword(userGuid, newPwd, areaCode);
                Print(rst ? "success" : "fail");
            }
        }

        /// <summary>
        /// 上报申请修改组织机构代码
        /// </summary>
        private void ResetOrginazationCode()
        {
            string corpUserGuid = currentUser.CorpUserGuid;
            string orgCode = _context.Request.Params["newGroupCode"];
            string areaCode = currentUser.CurrentArea;
            string orgGuid = _context.Request.Params["orgGuid"];
            int codeType = 1400;////聊城变更组织机构代码的classid
            int appID = 0;
            string appIDStr = ConfigurationManager.AppSettings["AppId"] != null ? ConfigurationManager.AppSettings["AppId"] : "";
            int.TryParse(appIDStr, out appID);

            if (!string.IsNullOrEmpty(_context.Request.Params["funcCode"]))
            {
                string funcCodes = _context.Request.Params["funcCode"].TrimEnd(',');
                string result0 = UtilitiesTool.IsFileExists(corpUserGuid, "EF", funcCodes);
                if (!string.IsNullOrEmpty(result0))
                {
                    Print("请先上传组织机构代码扫描件!");
                    return;
                }
            }

            using (EnterpriseService.EnterpriseServiceClient client = new EnterpriseService.EnterpriseServiceClient())
            {
                string operaStr = client.CorpOrgPost(orgCode, corpUserGuid, orgGuid, areaCode, codeType, appID, 4);
                OperationResult opera = JsonConvert.DeserializeObject<OperationResult>(operaStr);

                if (!string.IsNullOrEmpty(operaStr))
                {
                    //var rst = new { Result = opera.Result.ToString(), Message = opera.Message, Description = "", Tel = "Tel", Mail = "Email", RoleType = "RoleType" };
                    bool rst = opera.Result;
                    Print(rst ? "success" : "fail");
                }
                else
                {
                    Print("");
                }
            }
        }

        /// <summary>
        /// 从tb_flowcode表取得组织机构代码信息
        /// </summary>
        private void GetOrgData()
        {
            string corpUserGuid = currentUser.CorpUserGuid;
            string areaCode = currentUser.CurrentArea;
            int codeType = 1400;////聊城变更组织机构代码的classid
            int appID = 0;
            string appIDStr = ConfigurationManager.AppSettings["AppId"] != null ? ConfigurationManager.AppSettings["AppId"] : "";
            int.TryParse(appIDStr, out appID);

            using (EnterpriseService.EnterpriseServiceClient client = new EnterpriseService.EnterpriseServiceClient())
            {
                string flowCodeStr = client.GetCorpOrgByCorpUserGuid(corpUserGuid, areaCode, codeType, appID);
                Tb_FlowCode flowCode = JsonConvert.DeserializeObject<Tb_FlowCode>(flowCodeStr);

                if (flowCode != null && flowCode.Description != null && flowCode.FlowCode != null)
                {
                    string flowcodeStr = TranFlowCode(flowCode.FlowCode);
                    if (flowCode.FlowCode.StartsWith("1"))
                    {
                        var rst = new { FlowCodeStr = flowcodeStr };
                        Print(JsonConvert.SerializeObject(rst));
                    }
                    else
                    {
                        OrgInfo orgInfo = JsonConvert.DeserializeObject<OrgInfo>(flowCode.Description);
                        var rst = new { OrgCode = orgInfo.OrgCode, OrgGuid = orgInfo.OrgGuid, FlowCodeStr = flowcodeStr };
                        Print(JsonConvert.SerializeObject(rst));
                    }
                    
                }
                else
                {
                    Print("");
                }
            }
        }

        private string TranFlowCode(string flowCode)
        {
            string rst = string.Empty;
            switch (flowCode)
            {
                case "0":
                    rst = "未上报";
                    break;
                case "0,019":
                    rst = "上报";
                    break;
                case "0,019,021":
                    rst = "审核退回";
                    break;
                case "1,019,029":
                    rst = "审核通过";
                    break;
                default:
                    break;
            }
            return rst;
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }

        /// <summary>
        /// 输出数据到页面
        /// </summary>
        /// <param name="dataStr"></param>
        private void Print(string dataStr)
        {
            HttpContext.Current.Response.Clear();
            HttpContext.Current.Response.Write(dataStr);
            HttpContext.Current.Response.End();
        }
    }

    class OrgInfo
    {
        public string CorpName { get; set; }
        public string CorpUserGuid { get; set; }
        public string OrgCode { get; set; }
        public string OrgGuid { get; set; }
        public string PostDate { get; set; }
    }
}